package com.jeesit.cloud.spot.web.api_controller.material_top;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.dto.MaterialCatalogDto;
import com.jeesit.cloud.dto.MaterialTopDto;
import com.jeesit.cloud.spot.business.impl.IMaterialBiz;
import com.jeesit.cloud.spot.service.IMaterialCatalogService;
import com.jeesit.cloud.spot.service.IMaterialTopService;
import com.jeesit.cloud.verify.UserAuthDetail;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.util.ExportExcel;

import com.jeesit.cloud.validate.UpdateAction;
import com.jeesit.cloud.validate.CreateAction;
import com.jeesit.cloud.validate.QueryAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.jeesit.cloud.model.*;

import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jeesit.cloud.dto.JSONResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *   相关接口
 *　　
 *   @description MaterialTop 接口
 *   ---------------------------------
 *   @author 漆传涛
 *   @date 2024-01-08
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/v1/material_top")
@Api(tags = {"物料分类"})
public class MaterialTopController {

    @Autowired
    private IMaterialTopService materialTopService;

    @Autowired
    private IMaterialBiz materialBiz;

    @Autowired
    private IMaterialCatalogService materialCatalogService;

    /**
     * @description 获取分页列表
     * ---------------------------------
     * @author 漆传涛
     * @date 2024-01-08
     */
    @ApiOperation("获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataTypeClass = Integer.class , paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页行数，最少10条，最多100条", dataTypeClass = Integer.class , paramType = "query", required = true)
    })
    //@PreAuthorize("hasAnyAuthority('SUPER_ADMIN')")
    @PostMapping(value = "/material_top_page")
    public JSONResult<Page<MaterialTop>> getMaterialTopPage(Authentication authentication,@Validated(QueryAction.class) MaterialTopDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        Page<MaterialTop> page=new Page<MaterialTop>(dto.getPageNo(), dto.getPageSize());
        materialTopService.page(page,dto);
        JSONResult<Page<MaterialTop>> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(page);
        return res;
    }

/**
     * @description 获取列表
     * ---------------------------------
     * @author 漆传涛
     * @date 2024-01-08
     */
    @ApiOperation("获取列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
            @ApiImplicitParam(name = "size", value = "查询数量，最多查询1000条", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    //@PreAuthorize("hasAnyAuthority('SUPER_ADMIN')")
    @PostMapping(value = "/material_top_list")
    public JSONResult<MaterialTop> getMaterialTopList(Authentication authentication, @Validated(QueryAction.class)MaterialTopDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<MaterialTop> list = materialTopService.list(dto.getSize(),dto);
        JSONResult<MaterialTop> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setDatas(list);
        return res;
    }


    /**
     * @description 导出列表
     * ---------------------------------
     * @author 漆传涛
     * @date 2024-01-08
     */
    @ApiOperation("导出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('MaterialTop_Export','SUPER_ADMIN')")
    @PostMapping(value = "/material_top_export")
    public void export(HttpServletResponse response,Authentication authentication, @Validated(QueryAction.class)MaterialTopDto dto) {
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        List<MaterialTop> datas = materialTopService.list(0,dto);
        String[] header = new String[]{"物料分类","名称","机构ID  关联一级机构","创建人id","创建时间","修改人id","修改时间","",""};
        List<List<Object>> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("0.00");
        for(MaterialTop it : datas){
            List<Object> data = new ArrayList<>();
            data.add(it.getUuid());
            data.add(it.getName());
            data.add(it.getOrgUuid());
            data.add(it.getAddUserUuid());
            data.add(Optional.ofNullable(it.getAddTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getModUserUuid());
            data.add(Optional.ofNullable(it.getModTime()).map(s->sdf.format(s)).orElse(""));
            data.add(it.getDeleted());
            list.add(data);
        }
        ExportExcel excel = new ExportExcel();
        excel.setName("");
        excel.exportToExcel(response,header,list,0);
    }

    /**
     * @description 新建
     *
     * @author 漆传涛
     * @date 2024-01-08
     */
    @ApiOperation("新建")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('MaterialTop_Add','SUPER_ADMIN')")
    @ModuleLog("MaterialTop")
    @PostMapping("/material_top_add")
    public JSONResult<MaterialTop> saveNewEntity(HttpServletRequest request,Authentication authentication, @Validated(CreateAction.class) MaterialTopDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<MaterialTop> res= materialBiz.saveDataMaterialTop(user,null,entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "保存，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    /**
     * @description 更新
     *
     * @author 漆传涛
     * @date 2024-01-08
     */
    @ApiOperation("更新 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true)
    })
    @PreAuthorize("hasAnyAuthority('MaterialTop_Modify','SUPER_ADMIN')")
    @ModuleLog("MaterialTop")
    @PostMapping("/material_top_edit")
    public JSONResult<MaterialTop> saveEditEntity(HttpServletRequest request,Authentication authentication, MaterialTopDto entity){
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<MaterialTop> res= saveData(user,entity.getUuid(),entity);
        if(res.isSuccess()){
            request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "更新，数据ID:"+res.firstData().getUuid()));
        }
        return res;
    }

    private JSONResult<MaterialTop> saveData(User user,Long id,MaterialTopDto entity){
        JSONResult<MaterialTop> res = new JSONResult<>();
        MaterialTop it = new MaterialTop();
        if(id==null){
            it.setDeleted(false);
        } else {
            MaterialTopDto materialTopDto = new MaterialTopDto();
            materialTopDto.setNames(entity.getName());
            List<MaterialTop> list = materialTopService.list(1, materialTopDto);
            Assert.isTrue(list.size()==0||list.get(0).getUuid().equals(id),"物料分类已存在，请核对后重新输入");
            it = materialTopService.getById(entity.getUuid());
            it.setName(entity.getName());
        }
        materialTopService.saveOrUpdate(it);
        res.setData(it);
        res.setSuccess(true);
        res.setMessage("保存成功");
        return res;
    }


    /**
     * @description 删除
     *
     * @author 漆传涛
     * @date 2024-01-08
     */
    @ApiOperation("删除")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
        @ApiImplicitParam(name = "ids", value = "删除id（支持批量删除）", dataTypeClass = Long.class , allowMultiple = true,paramType = "query", required = true),
    })
    @PreAuthorize("hasAnyAuthority('MaterialTop_Remove','SUPER_ADMIN')")
    @ModuleLog("MaterialTop")
    @PostMapping("material_top_del")
        public JSONResult<Void> delEntity(HttpServletRequest request,Authentication authentication,@Size(min=1,max=50,message = "请选择要删除数据") Long[] ids) throws Exception{
        User user = ((UserAuthDetail)authentication.getPrincipal()).getUser();
        JSONResult<Void> res = new JSONResult<>();
        for(int i=0;i<ids.length;i++){
            MaterialTop it = materialTopService.getById(ids[i]);
            MaterialCatalogDto materialCatalogDto = new MaterialCatalogDto();
            materialCatalogDto.setMaterialTopUuid(ids[i]);
            List<MaterialCatalog> list = materialCatalogService.list(1, materialCatalogDto);
            Assert.isTrue(list.size()==0,it.getName()+"分类向下存在品类，请先删除品类");
            materialTopService.removeById(it.getUuid());
        }
        request.setAttribute(LogConstant.LOG_KEY,new LogInfo(user.getId(), "删除，数据ID:" + StringUtils.join(ids)));
        res.setMessage("删除成功");
        res.setSuccess(true);
        return res;
    }

    /**
     * @description : 获取树形结构列表
     * ---------------------------------
     *
     */
    @ApiOperation(value = "获取树形结构列表", notes = "获取树形结构列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "会话标识", dataType = "String", paramType = "header", required = true),
    })
    @PostMapping(value = "/tree_list")
    public JSONResult<JSONArray> getMaterialTopTreeList(HttpServletRequest request, Authentication authentication) {
        UserAuthDetail user = (UserAuthDetail)authentication.getPrincipal();
        //树形节点数据
        JSONArray treeArray = new JSONArray();
        List<MaterialTop> materialTops = materialTopService.list(0, new MaterialTopDto());
        for (MaterialTop it : materialTops) {
            JSONObject classObj = new JSONObject();
            classObj.put("uuid",it.getUuid());
            classObj.put("name",it.getName());
            classObj.put("type",0);
            //分类下的品类数据
            JSONArray childArray = new JSONArray();

            MaterialCatalogDto materialCatalogDto = new MaterialCatalogDto();
            materialCatalogDto.setMaterialTopUuid(it.getUuid());
            List<MaterialCatalog> materialCatalogs = materialCatalogService.list(0, materialCatalogDto);

            for (MaterialCatalog its : materialCatalogs) {
                JSONObject childObj = new JSONObject();
                childObj.put("uuid",its.getUuid());
                childObj.put("name",its.getName());
                childObj.put("type",1);
                childArray.add(childObj);
            }
            classObj.put("children",childArray);
            treeArray.add(classObj);
        }
        JSONResult<JSONArray> res = new JSONResult<>();
        res.setMessage("");
        res.setSuccess(true);
        res.setData(treeArray);
        return res;
    }


}

